package com.xbfinal.reggie.controller;


import com.xbfinal.reggie.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件的上传和下载
 */
@RestController
@RequestMapping("/common")
public class CommonController {

    //读取yml配置文件的位置
    @Value("${reggie.path}")
     private String basePath;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){

        //原始文件名
        final String originalFilename = file.getOriginalFilename();
        //获取 .jpg文件后缀
        final String substring = originalFilename.substring(originalFilename.lastIndexOf("."));

        //随机名
        String uuid=UUID.randomUUID().toString() +substring;
        //创建一个目录
        File file1 = new File(basePath);
        //判断目录是否存在
        if(!file1.exists()){
            //目录不存在就创建
            file1.mkdirs();
        }
        //将文件转存
        try{
            file.transferTo(new File(basePath+uuid));
        }catch (IOException e){

        }
        return R.success(uuid);//应该返回文件名 文件名前端或做相关的关联
    }

    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        //输入流读取文件内容
        final FileInputStream fileInputStream
                = new FileInputStream(new File(basePath+name));
        //输出流将文件写回浏览器
        final ServletOutputStream outputStream = response.getOutputStream();

        int len=0;
        byte[] bytes=new byte[1024];
        while ((len=fileInputStream.read(bytes)) != -1){
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }
        response.setContentType("image/jpg");

        //关闭流
        outputStream.close();
        fileInputStream.close();

    }
}
